package com.xiaoke.service.impl;

import com.wf.captcha.ArithmeticCaptcha;
import com.xiaoke.constants.RedisConstants;
import com.xiaoke.domain.R;
import com.xiaoke.domain.User;
import com.xiaoke.domain.dtos.LoginDto;
import com.xiaoke.domain.vos.LoginCodeVo;
import com.xiaoke.service.LoginService;
import com.xiaoke.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.UUID;
import java.util.concurrent.TimeUnit;

/**
 * @Author xiaoke
 * @Description 登录服务实现类
 * @Date 2023/7/24 13:16
 */
@Service
public class LogniServiceImpl  implements LoginService {

    @Autowired
    UserService userService;

    @Autowired
    RedisService redisService;

    @Override
    public R<String> login(LoginDto dto) {
        User user = userService.getByUserName(dto.getUsername());
        if(user == null || !user.getPassword().equals(dto.getPassword())) {
            return R.error("用户名或密码错误");
        }
        if(!verifyCode(dto.getKey(), dto.getCode())) {
            return R.error("验证码不存在或验证码错误");
        }
        //删除已经验证成功的验证码
        removeCode(dto.getKey());
        return R.ok("登录成功");
    }

    @Override
    public R<LoginCodeVo> code() {
        // 算术类型
        ArithmeticCaptcha captcha = new ArithmeticCaptcha(111, 36);
        // 几位数运算，默认是两位
        captcha.setLen(2);
        // 获取运算的结果
        String result = "";
        try {
            result = new Double(Double.parseDouble(captcha.text())).intValue() + "";
        } catch (Exception e) {
            result = captcha.text();
        }
        //生成uuid做为验证码的key
        UUID key = UUID.randomUUID();
        //存储验证码信息到redis中，60秒过期
        redisService.setCacheObject(RedisConstants.LOGIN_CODE+key,result,RedisConstants.LOGIN_CODE_TIME, TimeUnit.SECONDS);
        return R.ok(new LoginCodeVo(captcha.toBase64(),key.toString()));
    }

    /**
     * 验证验证码是否正确
     * @param key 验证码的key
     * @param code 验证码的结果
     */
    private boolean verifyCode(String key,String code) {
        String result = redisService.getCacheObject(RedisConstants.LOGIN_CODE + key);
        //验证码不存在直接返回null
        if(result == null) {
            return false;
        }
        return result.equals(code);
    }

    /**
     * 删除验证码
     * @param key 验证码Key
     */
    private void removeCode(String key){
        redisService.deleteObject(RedisConstants.LOGIN_CODE + key);
    }

}
